﻿using UnityEngine;
using System.Collections;

public class ShootAt : MonoBehaviour {

	public string tag = "Player";
	public GameObject target;
	public GameObject bullet;
	public float speed = 30f;
	public float rate = 0.2f;
	public float t = 0.2f;
	public float distance = 7f;
	
	// Use this for initialization
	void Start () {
	
	//if(target == null)
		
		
	}
	
	// Update is called once per frame
	void Update () {
	
	
		target = GameObject.FindGameObjectWithTag(tag);
		if(target == null)
		{
			return;
		}
		if(Vector2.Distance(target.transform.position, transform.position) < distance && target!=null)
		{
			LookAtZ(transform.parent.gameObject, target.transform.position);
			
			if(t <= 0f)
			{
				Vector3 dir = target.transform.position - transform.position;
				dir.Normalize();
				Vector3 raystart = transform.parent.transform.parent.position + dir*transform.parent.transform.parent.collider2D.bounds.size.x*2.1f;
				
				int temp = gameObject.layer;
				gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
				RaycastHit2D hit = Physics2D.Raycast(raystart,dir, distance);
				gameObject.layer=temp;
				
				if(hit.collider != null)
				{
					//print (hit.collider.gameObject.tag);
					if(hit.collider.gameObject.tag == tag)
					{
						//transform.parent.transform.LookAt(hit.collider.gameObject.transform.position);
						
						GameObject ob = Instantiate(bullet,transform.position,transform.rotation)as GameObject;
						ob.rigidbody2D.velocity = dir.normalized * speed;
						Destroy(ob,10f);
						
						LookAtZ(ob, target.transform.position);
						
						//ob.GetComponent<Bullet>().shooter = gameObject.tag;
						
						t = rate;
					}
				}
				
				
				
			}
			else
				t -= Time.deltaTime;
		}
		
			
	}
	
	void LookAtZ(GameObject ob, Vector3 target_pos)
	{
		Vector3 dir = target_pos-ob.transform.position;
		dir.Normalize();
		
		Quaternion target_q = ob.transform.rotation;
		
		if(dir.x > 0f && dir.x > Mathf.Abs(dir.y))// oikeelle
			target_q = Quaternion.LookRotation(target.transform.position - ob.transform.position,Vector3.down);
		if(dir.x < 0f && dir.x < -Mathf.Abs(dir.y))// vasemmalle
			target_q = Quaternion.LookRotation(target.transform.position - ob.transform.position,Vector3.up);
		
		if(dir.y > 0f && dir.y > Mathf.Abs(dir.x))// ylös
			target_q = Quaternion.LookRotation(target.transform.position - ob.transform.position,Vector3.right);
		if(dir.y < 0f && dir.y < -Mathf.Abs(dir.x))// alas
			target_q = Quaternion.LookRotation(target.transform.position - ob.transform.position,Vector3.left);
		
		target_q.x=0;
		target_q.y=0;
		
		ob.transform.rotation = target_q;
	}
}
